<template>
  <div class="container">
    <Breadcrumb :items="['站点管理', '充电桩管理', '充电枪管理']" />
    <a-card class="general-card" :title="deviceName ? `${deviceName} - 充电枪管理` : '充电枪管理'">
      <template #extra>
        <a-button type="primary" @click="goBack">
          <template #icon>
            <icon-arrow-left />
          </template>
          返回充电桩列表
        </a-button>
      </template>

      <!-- 操作栏 -->
      <div class="operation-bar">
        <a-button type="primary" @click="openAddDialog">
          <template #icon>
            <icon-plus />
          </template>
          新增充电枪
        </a-button>
      </div>

      <!-- 充电枪列表 -->
      <div class="gun-list">
        <a-row :gutter="[16, 16]">
          <a-col :span="6" v-for="gun in gunList" :key="gun.id">
            <a-card 
              class="gun-card" 
              hoverable
            >
              <div class="gun-header">
                <span class="gun-name">{{ gun.gunName }}</span>
              </div>

              <div class="gun-info">
                <div class="gun-icon">
                  <icon-charging />
                </div>
                <div class="gun-details">
                  <p><strong>充电枪编号:</strong> {{ gun.gunCode }}</p>
                  <p><strong>充电功率:</strong> {{ gun.maxPower }}kW</p>
                  <p><strong>充电类型:</strong> {{ getChargeTypeText(gun.gunType) }}</p>
                  <p><strong>创建时间:</strong> {{ formatTime(gun.createTime) }}</p>
                </div>
              </div>

              <div class="gun-actions">
                <a-space>
                  <a-button type="text" size="small" @click="viewGunDetail(gun)">
                    详情
                  </a-button>
                  <a-button type="text" size="small" @click="openEditDialog(gun)">
                    编辑
                  </a-button>
                  <a-button type="text" status="danger" size="small" @click="handleDelete(gun)">
                    删除
                  </a-button>
                </a-space>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>
    </a-card>

    <!-- 新增/编辑充电枪对话框 -->
    <a-modal
      v-model:visible="visible"
      :title="isEdit ? '编辑充电枪' : '新增充电枪'"
      @before-ok="handleSubmit"
      width="600px"
      :footer="false"
      class="gun-modal"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-align="left"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
        class="gun-form"
      >
        <a-form-item field="gunName" label="充电枪名称" required>
          <a-input v-model="form.gunName" placeholder="请输入充电枪名称" />
        </a-form-item>
        <a-form-item field="gunCode" label="充电枪编号" required>
          <a-input v-model="form.gunCode" placeholder="请输入充电枪编号" />
        </a-form-item>
        <a-form-item field="gunType" label="充电枪类型" required>
          <a-select v-model="form.gunType" placeholder="请选择充电枪类型">
            <a-option :value="1">国标</a-option>
            <a-option :value="2">欧标</a-option>
            <a-option :value="3">美标</a-option>
            <a-option :value="4">特斯拉</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="maxPower" label="最大功率" required>
          <a-input-number v-model="form.maxPower" placeholder="请输入最大功率" min="0" step="0.1">
            <template #append>kW</template>
          </a-input-number>
        </a-form-item>
        <a-form-item field="remark" label="备注说明">
          <a-textarea v-model="form.remark" placeholder="请输入备注说明" />
        </a-form-item>

        <div class="form-footer">
          <a-space>
            <a-button @click="visible = false">取消</a-button>
            <a-button type="primary" @click="handleSubmit">提交</a-button>
          </a-space>
        </div>
      </a-form>
    </a-modal>

    <!-- 充电枪详情对话框 -->
    <a-modal
      v-model:visible="detailVisible"
      title="充电枪详情"
      @cancel="detailVisible = false"
      :footer="false"
      width="700px"
    >
      <div v-if="currentGun" class="gun-detail">
        <a-descriptions :column="2" bordered size="large">
          <a-descriptions-item label="充电枪名称">{{ currentGun.gunName }}</a-descriptions-item>
          <a-descriptions-item label="充电枪编号">{{ currentGun.gunCode }}</a-descriptions-item>
          <a-descriptions-item label="充电类型">{{ getChargeTypeText(currentGun.gunType) }}</a-descriptions-item>
          <a-descriptions-item label="最大功率">{{ currentGun.maxPower }}kW</a-descriptions-item>
          <a-descriptions-item label="所属充电桩ID">{{ currentGun.pileId }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ formatTime(currentGun.createTime) }}</a-descriptions-item>
          <a-descriptions-item label="更新时间">{{ formatTime(currentGun.updateTime) }}</a-descriptions-item>
          <a-descriptions-item label="备注说明" :span="2">{{ currentGun.remark || '无' }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import { useRoute, useRouter } from 'vue-router';
import useLoading from '@/hooks/loading';
import axios from 'axios';
import type { FormInstance } from '@arco-design/web-vue';

// 充电枪数据接口
interface GunItem {
  id: number;
  createTime: string;
  updateTime: string;
  gunCode: string;
  gunName: string;
  pileId: number;
  gunType: number;
  maxPower: number;
  isDeleted: number;
  sortOrder: number;
  createBy: string;
  updateBy: string;
  remark: string;
}

// 获取路由参数
const route = useRoute();
const router = useRouter();
const deviceId = ref<number | null>(null);
const deviceName = ref<string>('');
const stationId = ref<number | null>(null);
const stationName = ref<string>('');

// 加载状态
const { loading, setLoading } = useLoading();

// 对话框状态
const visible = ref(false);
const detailVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance | null>(null);
const currentGun = ref<GunItem | null>(null);

// 充电枪列表
const gunList = ref<GunItem[]>([]);

// 表单数据
interface FormState {
  id?: number;
  gunName: string;
  gunCode: string;
  gunType: number;
  maxPower: number;
  remark: string;
  pileId: number;
}

const formInitialState: FormState = {
  gunName: '',
  gunCode: '',
  gunType: 1,
  maxPower: 0,
  remark: '',
  pileId: 0,
};

const form = reactive<FormState>({ ...formInitialState });

// 表单验证规则
const rules = {
  gunName: [{ required: true, message: '请输入充电枪名称' }],
  gunCode: [{ required: true, message: '请输入充电枪编号' }],
  gunType: [{ required: true, message: '请选择充电枪类型' }],
  maxPower: [{ required: true, message: '请输入最大功率' }],
};

// 获取充电枪类型文本
function getGunTypeText(type: number) {
  switch (type) {
    case 1:
      return '国标';
    case 2:
      return '欧标';
    case 3:
      return '美标';
    case 4:
      return '特斯拉';
    default:
      return '未知类型';
  }
}

// 获取充电类型文本
function getChargeTypeText(type: number) {
  return getGunTypeText(type);
}

// 格式化时间
function formatTime(time?: string) {
  if (!time) return '未知';
  return time.replace('T', ' ').substring(0, 19);
}

// 获取充电枪列表数据
async function fetchData() {
  if (!deviceId.value) {
    Message.error('充电桩ID不能为空');
    return;
  }
  
  setLoading(true);
  try {
    const response = await axios.get(`/api/charging/gun/pile/${deviceId.value}`);
    gunList.value = response.data;
  } catch (error) {
    console.error('获取充电枪列表失败:', error);
    Message.error('获取充电枪列表失败');
  } finally {
    setLoading(false);
  }
}

// 打开新增对话框
function openAddDialog() {
  isEdit.value = false;
  Object.assign(form, {
    ...formInitialState,
    pileId: deviceId.value || 0,
  });
  visible.value = true;
}

// 打开编辑对话框
function openEditDialog(gun: GunItem) {
  isEdit.value = true;
  Object.assign(form, {
    id: gun.id,
    gunName: gun.gunName,
    gunCode: gun.gunCode,
    gunType: gun.gunType,
    maxPower: gun.maxPower,
    remark: gun.remark || '',
    pileId: gun.pileId,
  });
  visible.value = true;
}

// 查看充电枪详情
function viewGunDetail(gun: GunItem) {
  currentGun.value = gun;
  detailVisible.value = true;
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) {
    console.error('表单引用不存在');
    return;
  }
  
  try {
    // 表单验证
    await formRef.value.validate();
    
    setLoading(true);
    
    if (isEdit.value) {
      // 编辑充电枪
      const params = {
        id: form.id,
        gunName: form.gunName,
        gunCode: form.gunCode,
        gunType: form.gunType,
        maxPower: form.maxPower,
        remark: form.remark,
        pileId: form.pileId,
      };
      
      try {
        await axios.put(`/api/charging/gun/${form.id}`, params);
        Message.success('编辑充电枪成功');
        visible.value = false;
        fetchData(); // 刷新列表
      } catch (error) {
        console.error('编辑充电枪失败:', error);
        Message.error('编辑充电枪失败');
      }
    } else {
      // 新增充电枪
      const params = {
        gunName: form.gunName,
        gunCode: form.gunCode,
        gunType: form.gunType,
        maxPower: form.maxPower,
        remark: form.remark,
        pileId: form.pileId,
      };
      
      try {
        await axios.post('/api/charging/gun', params);
        Message.success('新增充电枪成功');
        visible.value = false;
        fetchData(); // 刷新列表
      } catch (error) {
        console.error('新增充电枪失败:', error);
        Message.error('新增充电枪失败');
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    setLoading(false);
  }
};

// 删除充电枪
function handleDelete(gun: GunItem) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除充电枪 "${gun.gunName}" 吗？此操作不可恢复。`,
    onOk: async () => {
      setLoading(true);
      try {
        await axios.delete(`/api/charging/gun/${gun.id}`);
        Message.success('删除充电枪成功');
        fetchData(); // 刷新列表
      } catch (error) {
        console.error('删除充电枪失败:', error);
        Message.error('删除充电枪失败');
      } finally {
        setLoading(false);
      }
    },
  });
}

// 返回充电桩列表
function goBack() {
  const query: Record<string, any> = {};
  
  // 使用实例中保存的stationId和stationName
  if (stationId.value) {
    query.stationId = stationId.value;
  }
  
  if (stationName.value) {
    query.stationName = stationName.value;
  }
  
  // 跳转到充电桩列表页面，携带查询参数
  router.push({
    path: '/station/device',
    query
  });
}

onMounted(() => {
  // 获取路由参数
  if (route.query.deviceId) {
    deviceId.value = Number(route.query.deviceId);
  }
  if (route.query.deviceName) {
    deviceName.value = route.query.deviceName as string;
  }
  
  // 获取站点相关参数
  if (route.query.stationId) {
    stationId.value = Number(route.query.stationId);
  }
  if (route.query.stationName) {
    stationName.value = route.query.stationName as string;
  }
  
  // 获取充电枪列表
  fetchData();
});
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.operation-bar {
  margin-bottom: 16px;
}

.gun-list {
  margin-top: 16px;
}

.gun-card {
  height: 100%;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  }
  
  .gun-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .gun-name {
      font-size: 16px;
      font-weight: 500;
    }
  }
  
  .gun-info {
    display: flex;
    margin-bottom: 16px;
    
    .gun-icon {
      width: 60px;
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f2f3f5;
      border-radius: 8px;
      margin-right: 12px;
      
      :deep(svg) {
        font-size: 32px;
        color: #165dff;
      }
    }
    
    .gun-details {
      flex: 1;
      
      p {
        margin: 4px 0;
        font-size: 13px;
        color: #4e5969;
        
        strong {
          color: #1d2129;
        }
      }
    }
  }
  
  .gun-actions {
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #e5e6eb;
    padding-top: 12px;
    margin-top: 8px;
  }
}

.gun-modal {
  :deep(.arco-modal-header) {
    border-bottom: 1px solid var(--color-border-2);
    padding: 16px 20px;
    
    .arco-modal-title {
      font-size: 18px;
      font-weight: 500;
    }
  }
  
  :deep(.arco-modal-body) {
    padding: 20px;
  }
}

.gun-form {
  .form-footer {
    display: flex;
    justify-content: center;
    margin-top: 24px;
    
    .arco-space {
      .arco-btn {
        min-width: 80px;
      }
    }
  }
}

.gun-detail {
  :deep(.arco-descriptions) {
    background-color: var(--color-bg-2);
  }
}
</style> 